package cn.mumzone.pos.model.source;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;

import cn.mumzone.basic.mvp.BaseRepository;
import cn.mumzone.basic.net.http.callback.ApiCallBack;
import cn.mumzone.basic.net.response.BaseResponse;
import cn.mumzone.basic.net.response.PageListResponse;
import cn.mumzone.basic.net.source.AbsRepository;
import cn.mumzone.basic.util.DeviceIdUtils;
import cn.mumzone.basic.util.RxUtil;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.api.ApiRequest;
import cn.mumzone.pos.model.CardReturnEntity;
import cn.mumzone.pos.model.DepositGoodsEntity;
import cn.mumzone.pos.model.DepositGoodsRecordEntity;
import cn.mumzone.pos.model.IntegralRecordEntity;
import cn.mumzone.pos.model.LevelListEntity;
import cn.mumzone.pos.model.MemberAccountEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.MemberTicketEntity;
import cn.mumzone.pos.model.ReceiveDepositGoodEntity;
import cn.mumzone.pos.model.ReturnEntity;
import cn.mumzone.pos.model.SalesTimesCard;
import cn.mumzone.pos.model.TimeCardEntity;
import cn.mumzone.pos.model.TransactionRecordEntity;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Response;
import retrofit2.http.Query;

/**
 * Created by qiuzhenhuan on 2019/6/28.
 */

public class MemberRepository extends AbsRepository {

    public static final String SP_KEY_MEMBER_LEVEL = "member_level";

    /**
     * 创建新会员
     *
     * @param name
     * @param phone
     * @param gender
     * @param level
     * @param relation
     * @param status
     * @param dueDay
     * @param memberId
     * @param apiCallBack
     */
    public void createNewMember(String name, String phone, String gender, String level
            , String birthday, String relation, String status, String dueDay, String memberId,
                                ApiCallBack<MemberEntity> apiCallBack) {

        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("name", StringUtils.get(name));
        requestMap.put("phone", StringUtils.get(phone));
        requestMap.put("birthday", StringUtils.get(birthday));
        requestMap.put("gender", StringUtils.get(gender));
        requestMap.put("babyRelation", StringUtils.get(relation));
        requestMap.put("confinementDate", StringUtils.get(dueDay));
        requestMap.put("currentState", formatMemberState(status));
        requestMap.put("id", StringUtils.get(memberId));
        requestMap.put("levelId", StringUtils.get(level));
        requestMap.put("storeId", AppConstants.TEMP_SHOP_ID);
        ApiRequest.getMemberService()
                .createNewMember(requestMap)
                .compose(RxUtil.<Response<BaseResponse<MemberEntity>>>applySchedulers())
                .subscribe(apiCallBack);
    }

    /**
     * 获取对应的会员状态信息
     *
     * @param status
     * @return
     */
    private String formatMemberState(String status) {
        if ("怀孕中".equals(status)) {
            return "1";
        } else if ("已有宝宝".equals(status)) {
            return "2";
        } else if ("备孕中".equals(status)) {
            return "3";
        }
        return "";
    }

    public void getMemberInfoByPhone(String phone, ApiCallBack<MemberEntity> callBack) {
        ApiRequest.getMemberService()
                .getMemberInfoByPhone(phone)
                .compose(RxUtil.<Response<BaseResponse<MemberEntity>>>applySchedulers())
                .subscribe(callBack);
    }

    /**
     * 获取会员详情
     *
     * @param phone          手机号
     * @param memberCallback callback
     */
    public void getMemberDetailByPhone(String phone, ApiCallBack<MemberEntity> memberCallback) {
        ApiRequest.getMemberService()
                .getMemberDetailByPhone(phone)
                .compose(RxUtil.<Response<BaseResponse<MemberEntity>>>applySchedulers())
                .subscribe(memberCallback);
    }

    /**
     * 新建、编辑宝宝
     *
     * @param apiCallBack
     */
    public void createNewBaby(String babyName, String babyBirth, String babyHeight, String babyWeight,
                              String gender, String babyId, String memberId, String labour,
                              ApiCallBack<MemberEntity.BabysBean> apiCallBack) {

        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("name", babyName);
        requestMap.put("birthday", babyBirth);
        requestMap.put("height", babyHeight);
        requestMap.put("weight", babyWeight);
        requestMap.put("gender", gender);
        requestMap.put("id", babyId);
        requestMap.put("memberCompanyId", memberId);
        requestMap.put("labour", labour);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
                JSON.toJSONString(requestMap));
        ApiRequest.getMemberService()
                .createNewBaby(requestBody)
                .compose(RxUtil.<Response<BaseResponse<MemberEntity.BabysBean>>>applySchedulers())
                .subscribe(apiCallBack);
    }


    /**
     * 获取会员优惠券&体验券&次卡
     *
     * @param memberId 会员id
     * @param viewType 1券2次卡
     * @param page     页码
     * @param pageSize 每页个数
     */
    public void getTicketAllListPage(String memberId, String viewType, String page, String pageSize,
                                     ApiCallBack<MemberTicketEntity> ticketCallback) {
        ApiRequest.getMemberService()
                .getTicketAllListPage(memberId, viewType, page, pageSize)
                .compose(RxUtil.<Response<BaseResponse<MemberTicketEntity>>>applySchedulers())
                .subscribe(ticketCallback);
    }


    /**
     * 获取次卡列表
     *
     * @param memberId 会员id
     * @param viewType 1券 2次卡
     * @param page     页码
     * @param pageSize 每页个数
     */
    public void getTimesCardAllListPage(String memberId, String viewType, String page, String pageSize,
                                        ApiCallBack<PageListResponse<TimeCardEntity>> timeCardCallback) {
        ApiRequest.getMemberService()
                .getTimesCardAllListPage(memberId, viewType, page, pageSize)
                .compose(RxUtil.<Response<BaseResponse<PageListResponse<TimeCardEntity>>>>applySchedulers())
                .subscribe(timeCardCallback);
    }


    /**
     * 获取次卡详情&消费信息
     *
     * @param timeCardId
     * @param timeCardDetailCallback
     */
    public void getTimeCardDetail(String timeCardId, ApiCallBack<TimeCardEntity> timeCardDetailCallback) {
        ApiRequest.getMemberService()
                .getTimeCardDetail(timeCardId)
                .compose(RxUtil.<Response<BaseResponse<TimeCardEntity>>>applySchedulers())
                .subscribe(timeCardDetailCallback);
    }

    /**
     * 获取退卡详情
     *
     * @param timeCardDetailCallback
     */
    public void getReturnCardDetail(String timeCardId, String times, String residueTimes, String goodsId,
                                    String orderCode, ApiCallBack<CardReturnEntity> timeCardDetailCallback) {
        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("id", timeCardId);
        requestMap.put("times", times);
        requestMap.put("residueTimes", residueTimes);
        requestMap.put("goodsId", goodsId);
        requestMap.put("orderCode", orderCode);
        ApiRequest.getMemberService()
                .getReturnCardDetail(requestMap)
                .compose(RxUtil.<Response<BaseResponse<CardReturnEntity>>>applySchedulers())
                .subscribe(timeCardDetailCallback);
    }

    /**
     * 次卡退卡
     *
     * @param timeCardDetailCallback
     */
    public void returnCard(String returnId, String price, String residuePrice, String goodsId, String orderCode,
                           String returnMargin, ApiCallBack<List<ReturnEntity>> timeCardDetailCallback) {

        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("id", returnId);
        requestMap.put("residuePrice", residuePrice);
        requestMap.put("price", price);
        requestMap.put("goodsId", goodsId);
        requestMap.put("orderCode", orderCode);
        requestMap.put("returnMargin", returnMargin);
        requestMap.put("posCode", DeviceIdUtils.getDeviceId());
        ApiRequest.getMemberService()
                .returnCard(requestMap)
                .compose(RxUtil.<Response<BaseResponse<List<ReturnEntity>>>>applySchedulers())
                .subscribe(timeCardDetailCallback);
    }


    /**
     * 会员寄存商品信息
     *
     * @param memberCompanyId
     * @return
     */
    public void consignedGoods(String memberCompanyId, ApiCallBack<List<DepositGoodsEntity>> consignedGoodsCallback) {
        ApiRequest.getMemberService()
                .consignedGoods(memberCompanyId)
                .compose(RxUtil.<Response<BaseResponse<List<DepositGoodsEntity>>>>applySchedulers())
                .subscribe(consignedGoodsCallback);
    }

    /**
     * 领取寄存商品
     *
     * @return
     */
    public void receiveConsignedGoods(List<ReceiveDepositGoodEntity> list, ApiCallBack<String> apiCallBack) {
        String json = JSON.toJSONString(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orgId", AppConstants.TEMP_SHOP_ID);
        jsonObject.put("sellerId", AppConstants.TEMP_SELLER_ID);
        jsonObject.put("list", json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                JSON.toJSONString(jsonObject));
        ApiRequest.getMemberService()
                .receiveConsignedGoods(body)
                .compose(RxUtil.<Response<BaseResponse<String>>>applySchedulers())
                .subscribe(apiCallBack);
    }

    /**
     * 会员寄存商品领取记录
     *
     * @param orderCode
     * @param subCode
     * @param goodsId
     * @return
     */
    public void consignedGoodsReceiveRecord(String orderCode, String subCode, String goodsId,
                                            ApiCallBack<List<DepositGoodsRecordEntity>> consignedGoodsRecordCallback) {
        ApiRequest.getMemberService()
                .consignedGoodsReceiveRecord(orderCode, subCode, goodsId)
                .compose(RxUtil.<Response<BaseResponse<List<DepositGoodsRecordEntity>>>>applySchedulers())
                .subscribe(consignedGoodsRecordCallback);
    }


    /**
     * 获取可出售次卡列表
     *
     * @param pageNum
     * @param pageSize
     * @param timesCardCallback
     */
    public void getSaleTimeCardList(String pageNum, String pageSize,
                                    ApiCallBack<PageListResponse<SalesTimesCard>> timesCardCallback) {
        ApiRequest.getMemberService()
                .getSaleTimeCardList(pageNum, pageSize)
                .compose(RxUtil.<Response<BaseResponse<PageListResponse<SalesTimesCard>>>>applySchedulers())
                .subscribe(timesCardCallback);
    }

    /**
     * 获取会员等级
     *
     * @param apiCallBack
     */
    public void getMemberLevel(String orgId, ApiCallBack<List<LevelListEntity>> apiCallBack) {
        ApiRequest.getMemberService()
                .getMemberLevel(orgId)
                .compose(RxUtil.<Response<BaseResponse<List<LevelListEntity>>>>applySchedulers())
                .subscribe(apiCallBack);
    }


    /**
     * 会员交易记录
     *
     * @param type
     * @param memberId
     * @param dateTime
     * @param pageNum
     * @param pageSize
     * @param apiCallBack
     */
    public void selectTransactionRecord(String type, String memberId, String dateTime, String pageNum, String pageSize,
                                        ApiCallBack<PageListResponse<TransactionRecordEntity>> apiCallBack) {
        ApiRequest.getMemberService()
                .selectTransactionRecord(type, memberId, dateTime, pageNum, pageSize)
                .compose(RxUtil.<Response<BaseResponse<PageListResponse<TransactionRecordEntity>>>>applySchedulers())
                .subscribe(apiCallBack);
    }


    public void selectIntegralRecord(String type, String memberId, String dateTime, String pageNum, String pageSize,
                                        ApiCallBack<PageListResponse<IntegralRecordEntity>> apiCallBack) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", type);
        jsonObject.put("memberCompanyId", memberId);
        jsonObject.put("date", dateTime);
        jsonObject.put("pageNo", pageNum);
        jsonObject.put("pageSize", pageSize);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                JSON.toJSONString(jsonObject));
        ApiRequest.getMemberService()
                .selectIntegralRecord(body)
                .compose(RxUtil.<Response<BaseResponse<PageListResponse<IntegralRecordEntity>>>>applySchedulers())
                .subscribe(apiCallBack);
    }



    /**
     * 获取会员支付账户信息
     *
     * @param apiCallBack
     */
    public void getMemberStoreList(String memberId, ApiCallBack<MemberAccountEntity> apiCallBack) {
        ApiRequest.getMemberService()
                .getMemberStoreList(memberId)
                .compose(RxUtil.<Response<BaseResponse<MemberAccountEntity>>>applySchedulers())
                .subscribe(apiCallBack);
    }

    /**
     * 会员等级
     *
     * @param memberLevelList
     */
    public void saveMemberLevel(List<LevelListEntity> memberLevelList) {
        mSPManager.put(SP_KEY_MEMBER_LEVEL, JSON.toJSONString(memberLevelList));
        AppConstants.TEMP_MEMBER_LEVEL = JSON.toJSONString(memberLevelList);
    }


}
